package com.lvt.example.thinking.in.spring.ioc.overview.dependency.injection;

import com.lvt.example.thinking.in.spring.ioc.overview.repository.UserRepository;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.env.Environment;

/**
 * 依赖注入示例：
 * 1、根据 Bean 名称注入
 * 2、根据 Bean 类型注入
 * 单个 Bean 对象
 * 集合 Bean 对象
 *
 * @author LT
 * @date 2021/4/18
 */
public class DependencyInjectionDemo {

    public static void main(String[] args) {
        BeanFactory applicationContext = new ClassPathXmlApplicationContext("classpath:META-INF/dependency-injection-context.xml");
//        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:META-INF/dependency-injection-context.xml");

        // 依赖来源一：自定义 Bean
        UserRepository userRepository = applicationContext.getBean("userRepository", UserRepository.class);
        System.out.println(userRepository.getUsers());

        // 依赖来源二：依赖注入（內建依赖）
        System.out.println(userRepository.getBeanFactory());
        ObjectFactory userFactory = userRepository.getObjectFactory();
        System.out.println(userFactory.getObject() == applicationContext); // true

        // 依赖查找（错误）
//        System.out.println(beanFactory.getBean(BeanFactory.class));

        // 依赖来源三：容器內建 Bean
        Environment environment = applicationContext.getBean(Environment.class);
        System.out.println("获取 Environment 类型的 Bean：" + environment);

    }

    private static void whoIsIocContainer(UserRepository userRepository, ApplicationContext applicationContext) {

        // ConfigurableApplicationContext <- ApplicationContext <- BeanFactory
        // ConfigurableApplicationContext#getBeanFactory()
        // 这个表达式为什么不会成立
        System.out.println(userRepository.getBeanFactory() == applicationContext);
        // ApplicationContext is BeanFactory,组合方式，并非同一对象
    }

}
